package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.entity.CategoryBrandRelationEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gulimall.common.utils.PageUtils;
import com.atguigu.gulimall.common.utils.Query;

import com.atguigu.gulimall.product.dao.BrandDao;
import com.atguigu.gulimall.product.entity.BrandEntity;
import com.atguigu.gulimall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(key)) {
            wrapper.eq("brand_id", key).or().like("name", key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }


    @Override
    @Transactional //开启事务
    public void updateBrand(BrandEntity brand) {
        this.updateById(brand);
        // 更新关联表
        categoryBrandRelationService.updateBrand(brand.getBrandId(), brand.getName());
    }


    @Override
    public List<BrandEntity> getCategoryBrandRelationList(Long catId) {
        // 通过当前分类id，在关联表中获取对应的品牌id
        List<CategoryBrandRelationEntity> categoryBrandRelationEntities = categoryBrandRelationService.list(new QueryWrapper<CategoryBrandRelationEntity>().eq("catelog_id", catId));
        // 第一种
        List<Long> brandIds = categoryBrandRelationEntities.stream().map((item) -> {
            return item.getBrandId();
        }).collect(Collectors.toList());
        List<BrandEntity> brandEntityList = null;
        if (brandIds != null && brandIds.size() > 0) {
            brandEntityList = this.baseMapper.selectBatchIds(brandIds);
        }
        return brandEntityList;
    }

}